package com.zysoft.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.core.io.Resource;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Controller
public class UI {
    @Autowired
    private HttpServletRequest req;

    @Autowired
    private HttpServletResponse res;

    @RequestMapping("/index")
    public String index()
    {
        return "index";
    }

    @RequestMapping("/test")
    public String test()
    {
        return "upload";
    }

    @RequestMapping("/uploadDir")
    public String uploadDir() throws IOException {
        //return ResourceUtils.getFile("/static/demo.js").getPath();
        //String resourcePath = this.getClass().getResource("/static/demo.js").getPath();
        //return  resourcePath;
        String path = this.getClass().getClassLoader().getResource("").getPath();
        String projectPath = System.getProperty("user.dir");

        return projectPath;
    }

    @RequestMapping(value="/upload",method = RequestMethod.POST)
    @ResponseBody
    public String f_post(@RequestParam(value="file",required=true)MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String dir = ResourceUtils.getURL("classpath:").getPath() + "static/uploads/";

        if(dir.startsWith("/")) dir = dir.substring(1);

        Path dic = Paths.get(dir);

        if(!java.nio.file.Files.exists(dic))
        {
            Files.createDirectory(dic);
        }

        String filePath = dir +  fileName;// 设定保存路径
        file.transferTo(new File(filePath));
        return "/static/uploads/"+fileName;
    }
}
